// let wxCharts = require("../utils/wxcharts.js");
import * as echarts from '../ec-canvas/echarts'; 

var columnChart = null;
const app = getApp();

function setOption(chart, lowMotion, inMotion, highMotion) {
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            data: ['低活动强度','中活动强度','高活动强度']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
          data: ['00点', '01点', '02点', '03点', '04点', '05点', '06点', '07点', '08点', '09点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点']
        },
        yAxis: {
            type: 'value',
      }, 
      series: [
        {
          name: '低强度',
          type: 'bar',
          stack: '总量',
          data: lowMotion,
          color: '#F6B92B'
        },
        {
          name: '中强度',
          type: 'bar',
          stack: '总量',
          data: inMotion,
          color: '#F99225'
        },
        {
          name: '高强度',
          type: 'bar',
          stack: '总量',
          data: highMotion,
          color: '#F8C8C5'
        },
      ],
      animation: false,
    };

    chart.setOption(option);
    return chart;
}

/**
 * 周假数据
 */
function setWeekOption(chart, lowMotion, inMotion, highMotion) {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    legend: {
      data: ['低活动强度', '中活动强度', '高活动强度']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '低强度',
        type: 'bar',
        stack: '总量',
        data: lowMotion,
        color: '#F6B92B'
      },
      {
        name: '中强度',
        type: 'bar',
        stack: '总量',
        data: inMotion,
        color: '#F99225'
      },
      {
        name: '高强度',
        type: 'bar',
        stack: '总量',
        data: highMotion,
        color: '#F6541E'
      },
    ],
    animation: false,
  };

  chart.setOption(option);
  return chart;
}

/**
 * 月假数据
 */
function setMonthOption(chart, lowMotion, inMotion, highMotion) {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    legend: {
      data: ['低活动强度', '中活动强度', '高活动强度']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24','25', '26', '27', '28', '29', '30']
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '低强度',
        type: 'bar',
        stack: '总量',
        data: lowMotion,
        color: '#F6B92B'
      },
      {
        name: '中强度',
        type: 'bar',
        stack: '总量',
        data: inMotion,
        color: '#F99225'
      },
      {
        name: '高强度',
        type: 'bar',
        stack: '总量',
        data: highMotion,
        color: '#F6541E'
      },
    ],
    animation: false,
  };

  chart.setOption(option);
  return chart;
}

// data/ShowData.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dataList: [{
            name: '周',
            isChoose: true
        }, {
            name: '月',
            isChoose: false
        }, {
            name: '年',
            isChoose: false
        }],
        nowDate:'2018年7月22日-7月29日',
        nowDay: 29,
        nowWeekDay: 7,
        chooseIndex:0,
        changeIndex:0,  //用户点击上一步和下一步总计的操作，-3则代表在当前时间单位前跳3个时间单位，5则代表在当前时间单位后跳5个时间单位，0则无操作
        lowMotion: [],// 低强度
        inMotion: [],// 中强度
        highMotion: [], // 高强度
        deviceDatas:[],
        ec: {
          lazyLoad: true// 懒加载 柱状图
        },
    },

    chooseData: function (e) {
        this.data.changeIndex = 0;
        let index = e.target.dataset.index;
        let dataList = this.data.dataList;
        for (let i = 0, len = dataList.length;i<len;i++){
            dataList[i].isChoose = false;
        }
        dataList[index].isChoose = true;
        this.setData({
            dataList: dataList,
            chooseIndex: index
        });
        this.getNowDate(index);
        switch (index) {
            // case 0:
            //     this.changeDayTime(0);
            //     break;
            case 0:
                this.changeWeekTime(0);
                break;
            case 1:
                this.changeMonthTime(1);
                break;
            case 2:
                this.changeYearTime(2);
                break;
        }
    },
    //获取当前时间
    getNowDate:function(index){
        //当下时间
        let nowTime = new Date();
        let nowMonth = nowTime.getMonth() + 1;
        let nowYear = nowTime.getFullYear();
        let nowDay = nowTime.getDate();
        let sevenDayLatyTime = new Date(nowTime.getTime() + 24 * 7 * 60 * 60 * 1000);
        let sevenDayLatyMonth = sevenDayLatyTime.getMonth() + 1;
        let sevenDayLatyDay = sevenDayLatyTime.getDate();
        this.handleNowDate(index, nowYear, nowMonth, nowDay, sevenDayLatyMonth, sevenDayLatyDay);
    },
    //变动以日为单位的时间
    changeDayTime:function(index){
      let nowTime = new Date(new Date().getTime() + (this.data.changeIndex * 24) * 60 * 60 * 1000);
      let nowMonth = nowTime.getMonth() + 1;
      let nowYear = nowTime.getFullYear();
      let nowDay = nowTime.getDate();
      this.handleNowDate(index, nowYear, nowMonth, nowDay);

      // 切换统计图
      this.data.lowMotion = [];
      this.data.inMotion = [];
      this.data.highMotion = [];
      for (let i = 0; i < 24; i++) {
        // if (i < 6 || i > 20) {
        //   this.data.lowMotion[i] = 119;
        //   this.data.inMotion[i] = 1;
        //   this.data.highMotion[i] = 0;
        // } else {
          // var randomLow = Math.floor(Math.random() * 20 + 20);
          // var randomIn = Math.floor(Math.random() * 25 + 15);
          // var randomHigh = Math.floor(Math.random() * 30 + 10);
          var randomLow = 0;
          var randomIn = 0;
          var randomHigh = Math.floor(Math.random() * 80 + 40);
          this.data.lowMotion[i] = randomLow;
          this.data.inMotion[i] = randomIn;
          this.data.highMotion[i] = randomHigh;
        // }
      }
      this.ecComponent.init((canvas, width, height) => {
        // 获取组件的 canvas、width、height 后的回调函数
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        setOption(chart, this.data.lowMotion, this.data.inMotion, this.data.highMotion);

        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;

        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });

      wx.hideLoading();
    },
    //变动已周为单位的时间
    changeWeekTime:function(index){
        wx.showLoading({
          title: '生成统计结果，请稍等...',
        });

        let nowTime = new Date(new Date().getTime() + (this.data.changeIndex * 24*7) * 60 * 60 * 1000);
        let nowMonth = nowTime.getMonth() + 1;
        let nowYear = nowTime.getFullYear();
        let nowDay = nowTime.getDate();
        let sevenDayLatyTime = new Date(nowTime.getTime() + 24 * 7 * 60 * 60 * 1000);
        let sevenDayLatyMonth = sevenDayLatyTime.getMonth()+1;
        let sevenDayLatyDay = sevenDayLatyTime.getDate();
        this.handleNowDate(index, nowYear, nowMonth, nowDay, sevenDayLatyMonth, sevenDayLatyDay);

        // 切换统计图
        this.data.lowMotion = [];
        this.data.inMotion = [];
        this.data.highMotion = [];
        for (let i = 0; i < this.data.nowWeekDay; i++) {
          if (i == this.data.nowWeekDay){
            this.data.lowMotion[i] = 25;
            this.data.inMotion[i] = 26;
            this.data.highMotion[i] = 10;
          }else{
            var randomLow = Math.floor(Math.random() * 300 + 180);
            var randomIn = Math.floor(Math.random() * 380 + 100);
            var randomHigh = Math.floor(Math.random() * 450 + 30);
            this.data.lowMotion[i] = randomLow;
            this.data.inMotion[i] = randomIn;
            this.data.highMotion[i] = randomHigh;
          }
        }
        this.ecComponent.init((canvas, width, height) => {
          // 获取组件的 canvas、width、height 后的回调函数
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height
          });
          setWeekOption(chart, this.data.lowMotion, this.data.inMotion, this.data.highMotion);

          // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
          this.chart = chart;

          // 注意这里一定要返回 chart 实例，否则会影响事件处理等
          return chart;
        });

        wx.hideLoading();
    },
    //变动以月为单位的时间
    changeMonthTime:function(index){
      wx.showLoading({
        title: '生成统计结果，请稍等...',
      });

      let nowTime = new Date(new Date().getTime() + (this.data.changeIndex * 24 * 30) * 60 * 60 * 1000);
      let nowMonth = nowTime.getMonth() + 1;
      let nowYear = nowTime.getFullYear();
      this.handleNowDate(index, nowYear, nowMonth);

      // 切换统计图
      this.data.lowMotion = [];
      this.data.inMotion = [];
      this.data.highMotion = [];
      for (let i = 0; i < this.data.nowDay; i++) {
        if (i == this.data.nowDay){
          this.data.lowMotion[i] = 25;
          this.data.inMotion[i] = 26;
          this.data.highMotion[i] = 10;
        }else{
          var randomLow = Math.floor(Math.random() * 180 + 300);
          var randomIn = Math.floor(Math.random() * 300 + 180);
          var randomHigh = Math.floor(Math.random() * 400 + 80);
          this.data.lowMotion[i] = randomLow;
          this.data.inMotion[i] = randomIn;
          this.data.highMotion[i] = randomHigh;
        }
      }

      this.ecComponent.init((canvas, width, height) => {
        // 获取组件的 canvas、width、height 后的回调函数
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        setMonthOption(chart, this.data.lowMotion, this.data.inMotion, this.data.highMotion);

        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;

        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });

      wx.hideLoading();
    },
    //变动以年为单位的时间
    changeYearTime:function(index){
        let nowTime = new Date();
        let nowYear = nowTime.getFullYear() + this.data.changeIndex;
        this.handleNowDate(index, nowYear);
    },
    //处理当前时间
    handleNowDate: function (index, nowYear, nowMonth, nowDay, sevenDayLatyMonth, sevenDayLatyDay){
        let finalDate = '';
        switch (index) {
            // case 0:
            //     finalDate = `${nowYear}年${nowMonth}月${nowDay}日`;
            //     break;
            case 0:
                finalDate = `${nowYear}年${nowMonth}月${nowDay}日-${sevenDayLatyMonth}月${sevenDayLatyDay}日`;
                break;
            case 1:
                finalDate = `${nowYear}年${nowMonth}月`;
                break;
            case 2:
                finalDate = `${nowYear}年`
                break;
        }
        this.setData({
            nowDate: finalDate,
        })
    },
    //点击向前跳时间
    prevTime:function(){
        this.data.changeIndex --;
        switch (this.data.chooseIndex) {
            // case 0:
            //     this.changeDayTime(0);
            //     break;
            case 0:
                this.changeWeekTime(0);
                break;
            case 1:
                this.changeMonthTime(1);
                break;
            case 2:
                this.changeYearTime(2);
                break;
        }
    },
    //点击向后跳时间
    nextTime:function(){
        this.data.changeIndex ++;
        switch (this.data.chooseIndex) {
            // case 0:
            //     this.changeDayTime(0);
            //     break;
            case 0:
                this.changeWeekTime(0);
                break;
            case 1:
                this.changeMonthTime(1);
                break;
            case 2:
                this.changeYearTime(2);
                break;
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      // 获取组件
      this.ecComponent = this.selectComponent('#mychart-dom-bar');

      this.dayDataSet();
    },

    dayDataSet(){
      var that = this;
      
      wx.showLoading({
        title: '生成统计结果，请稍等...',
      });

      // 1、拿到当天的数据 处理 展示到柱状图中
      try {
        var date = new Date();
        var dayKey = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
        var value = wx.getStorageSync(dayKey);

        if (value) {
          this.data.deviceDatas = value;
        }
      } catch (e) {
        console.log('获取数据异常');
      }

      // if (null != this.data.deviceDatas && this.data.deviceDatas.length > 0) {
      //   // 2、构造24小时的数据结构
      //   for (let i = 0; i < 24; i++) {
      //     this.data.lowMotion.push(0);
      //     this.data.inMotion.push(0);
      //     this.data.highMotion.push(0);
      //   }

      //   // 3、根据起始时间构造每个小时的数据 通过步数计算高、中、低强度运动，展示的是体能
      //   for (let i = 0; i < this.data.deviceDatas.length; i++) {
      //     var hour = parseInt(value[i].startHour + (i / 120) + (value[i].startMin / 60));
      //     if (value[i].stepNumber < 5) {
      //       this.data.lowMotion[hour]++;
      //     } else if (value[i].stepNumber < 10 && value[i].stepNumber >= 5) {
      //       this.data.inMotion[hour]++;
      //     } else if (value[i].stepNumber >= 10) {
      //       this.data.highMotion[hour]++;
      //     }
      //   }

      //   this.ecComponent.init((canvas, width, height) => {
      //     // 获取组件的 canvas、width、height 后的回调函数
      //     const chart = echarts.init(canvas, null, {
      //       width: width,
      //       height: height
      //     });
      //     setOption(chart, this.data.lowMotion, this.data.inMotion, this.data.highMotion);

      //     // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      //     this.chart = chart;

      //     // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      //     return chart;
      //   });
      // }else{
          // 切换统计图
          this.data.lowMotion = [];
          this.data.inMotion = [];
          this.data.highMotion = [];
          for (let i = 0; i < this.data.nowWeekDay; i++) {
            if (i == this.data.nowWeekDay) {
              this.data.lowMotion[i] = 25;
              this.data.inMotion[i] = 26;
              this.data.highMotion[i] = 10;
            } else {
              var randomLow = Math.floor(Math.random() * 300 + 180);
              var randomIn = Math.floor(Math.random() * 380 + 100);
              var randomHigh = Math.floor(Math.random() * 450 + 30);
              this.data.lowMotion[i] = randomLow;
              this.data.inMotion[i] = randomIn;
              this.data.highMotion[i] = randomHigh;
            }
          }
          this.ecComponent.init((canvas, width, height) => {
            // 获取组件的 canvas、width、height 后的回调函数
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            setWeekOption(chart, this.data.lowMotion, this.data.inMotion, this.data.highMotion);

            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;

            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
          });
      // }
      wx.hideLoading();
    }
})